
# If you have any questions, please contact williammu@tencent.com

from Tkinter import *
from tkSimpleDialog import *
import re

class PaintWindow( Frame ):
	def __init__( self, parent, **kwArgs ):
		Frame.__init__( self, parent, kwArgs )
		self.canvas = None
		self.createCanvas()
		self.curFrame = 0
		
		fp = open("log.txt", "r")
		lines = fp.readlines()
		fp.close()
		
		self.slopeData = self.getSlopeData(lines)
		print self.slopeData
		self.polygonData = self.getPolygonData(lines)
		print self.polygonData
		
		for coord in self.slopeData:
			x1 = coord[0][0]
			y1 = coord[0][1]
			
			x2 = coord[1][0]
			y2 = coord[1][1]
			
			self.drawLine(x1, y1, x2, y2)
			
	
	def getSlopeData(self, lines):
		result = []
		for l in lines:
			if len(l) == 1:
				break
			l = l.replace("\n", "")
			ary = l.split(" ")
			x1 = float(ary[0])
			y1 = float(ary[1])
			x2 = float(ary[2])
			y2 = float(ary[3])
			
			result.append(((x1, y1),(x2, y2)))
		return result;
	
	def getPolygonData(self, lines):
		result = []
		raw = []
		tmp = []
		valid = False
		for l in lines:
			if not valid and len(l) == 1:
				valid = True
			elif not valid:
				continue
			
			if len(l) == 1:
				if len(tmp):
					raw.append(tmp)
				tmp = []
				continue
			
			tmp.append(l)
		raw.append(tmp) #don't forget the last one
		
		for r in raw:
			lst = []
			for i in xrange(0, 5):
				r[i] = r[i].replace("\n", "")
				ary = r[i].split(" ")
				x = float(ary[0])
				y = float(ary[1])
				lst.append((x, y))
			result.append(lst)
		return result
	
	def renderNextFrame(self, evt):
		poly = self.polygonData[self.curFrame]
		x1 = poly[0][0]
		y1 = poly[0][1]
		
		x2 = poly[1][0]
		y2 = poly[1][1]
		
		x3 = poly[2][0]
		y3 = poly[2][1]
		
		x4 = poly[3][0]
		y4 = poly[3][1]
		
		self.drawLine(x1, y1, x2, y2)
		self.drawLine(x2, y2, x3, y3)
		self.drawLine(x3, y3, x4, y4)
		self.drawLine(x4, y4, x1, y1)
		
		gX = poly[4][0]
		gY = poly[4][1]
		
		self.drawLine(gX-0.5, gY-0.5, gX+0.5, gY+0.5)
		
		self.curFrame += 1
		
	def createCanvas( self ):
		frame = Frame( self )
		frame.pack( expand = YES, fill = BOTH )
		canvas = Canvas( frame, takefocus = True, borderwidth = 0, highlightthickness = 0)
		self.canvas = canvas
		canvas.bind( "<Control-d>", self.renderNextFrame )
		canvas.pack( expand = YES, fill = BOTH )

		canvas.focus_set()

	def drawLine(self, x1, y1, x2, y2):
		scale = 4.0
		x1 = x1 * scale;
		y1 = y1 * scale;
		x2 = x2 * scale;
		y2 = y2 * scale;
		x1 = x1 + 400
		x2 = x2 + 400
		y1 = 768 - y1 - 400
		y2 = 768 - y2 - 400
		self.canvas.create_line(x1 , y1 , x2 , y2 )



if __name__ == '__main__':
	root = Tk()
	root.geometry( '1024x768+20+20')	
	root.title( "ACM Painter v0.1" )
	PaintWindow( root ).pack( expand = YES, fill = BOTH )

	mainloop()
